package com.feng.leetcode;

/**
 * @author feng
 * @decrition
 * @date 2022/10/3123:53
 */
public class L481 {
    public int magicalString(int n) {
        StringBuilder sb = new StringBuilder("122");
        if (n <= 3) {
            return 1;
        }
        // 表示当前是1还是2 默认为1
        boolean flag = true;
        // 表示当前的索引 默认为2
        int index = 2;
        int count = 1;
        for (; sb.length() <= n; index++) {
            char c = sb.charAt(index);
            if (flag) {
                if ('1' == c) {
                    sb.append("1");
                    flag = !flag;
                    count++;
                    continue;
                }
                sb.append("1");
                sb.append("1");
                count += 2;
                flag = !flag;
            } else {
                if ('1' == c) {
                    sb.append("2");
                    flag = !flag;
                    continue;
                }
                sb.append("2");
                sb.append("2");
                flag = !flag;
            }
        }
        String substring = sb.substring(n);
        for (int i = 0; i < substring.length(); i++) {
            if ('1' == substring.charAt(i)) {
                count--;
            }
        }
        return count;
    }
}
